# -*- coding: utf8 -*-

from puppy.result import ResultFilter
import subprocess

# Enable relative paths:
import os
rel = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)

class SuitabilityFilter(ResultFilter):
  """
  Filters search results based on the results' suitability for children.
  
  Options:
  
  * threshold (double): confidence score to accept a page (e.g. 0.5)
  """
  
  def __init__(self, options=""):
    """Constructor for SuitabilityFilter."""
    super(SuitabilityFilter, self).__init__(options)
    self.info = "Filters search results based on the results' suitability for children."
  
  
  def run(self, results):
    '''
    Filters the document list according to child suitability.
    
    Keeps only documents with a suitability confidence >= the specified threshold confidence.
    
    Parameters:
      
    * results (puppy.model.Opensearch.Response): results to be filtered
    
    Returns:
    
    * results (puppy.model.Opensearch.Response): filtered results
      
    TODO convert to using puppy.model.Opensearch.Response
    '''
    # Concatenate urls to classifier input string
    input = ""
    docs = results['documents']
    for doc in docs:
      input += doc['url']+" "
    
    # Call classifier
    absolutePath = os.path.abspath(os.path.dirname(__file__))+"/"
    p1 = subprocess.Popen(["java", "-jar", rel("suitability_url.jar"), "-p", absolutePath, input], stdout=subprocess.PIPE)
    output = p1.stdout.read()
    suitabilityScores = output.split("\n")
    
    # Reject unsuitable documents
    result = {'resultcount' : 0, 'totalcount' : results['totalcount'], 'documents': []}        
    for i in range(0,len(suitabilityScores)):
      if len(suitabilityScores[i]) > 4:
        score = suitabilityScores[i][suitabilityScores[i].find(" -> ")+4:len(suitabilityScores[i])]
        if float(score) >= float(self.options['threshold']):
          result['resultcount'] += 1
          result['documents'].append(results['documents'][i])
    
    # Return the filtered dictionary
    return result
  
